var http = require('../../../../script/api.js');
var config = require('../../../../script/config.js')
var context = null; // 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false; //是否在绘制中
var arrx = []; //动作横坐标
var arry = []; //动作纵坐标
var arrz = []; //总做状态，标识按下到抬起的一个组合
var canvasw = 0; //画布宽度
var canvash = 0; //画布高度

Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    orderinfo: {
      type: Object,
      value: null
    },
  },
  observers: {
    'orderinfo': function (val) {
      if (val != null) {
        this.setDefaultValue();
        this.GetComplainCount();
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    ProcHandReasonList: [],
    SolveWayList: [],
    SubmitData: {
      SOLVEWAY: '',
      SOLVEREMARK: '',
      ProcHandReason: '',
      OTHERREASON: '',
      BeginTime: '',
      EndTime: '',
      HeatSide1Temp: null,
      HeatSide1BackTemp: null,
      HeatSide2Temp: null,
      HeatSide2BackTemp: null,
      OuterTemp: null,
      DeviceTemp: null,
      LivingRoomTemp: null,
      BedroomTemp: null,
      SupplyTemp: null,
      ReturnTemp: null,
      NormalFlag: '0',
      PetitionFlag: '0',
      ACCUMBACKFEEDAYS: null,
      COMPLAINCOUNT: null,
    },
    /********电子签名相关********/
    // canvasw: '',
    // canvash: '',
    signUrl: '', // 签名本地地址
    signSurl: '', // 签名上传服务器地址
    // info: {},
    signBase64: '',
    sysType: '', // 判断机型
    showUserSign: false,
    baseUrl: config.baseUrl,
    /********电子签名相关********/
  },
  lifetimes: {
    attached() {
      this.getList('ProcHandReason');
      this.getList('SolveWay');

      /********电子签名 *********/
      let that = this
      let res = wx.getSystemInfoSync()
      const system = res.system.split(' ')
      that.setData({
        sysType: system[0],
      })
      that.startCanvas();
      that.initCanvas();
      /********电子签名 *********/
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getList(type) {
      http.GetPCodeList({
        CODE_TYPE: type,
      }).then(res => {
        if (res.code === 200) {
          const resData = res.data || [];
          const list = resData.find(item => item.VALUE === '004');
          if (list) {
            const children = [...list.Childrens];
            children.push({NAME: '其他',VALUE: '099'});
            if (type === 'ProcHandReason') {
              this.setData({
                ProcHandReasonList: children,
                // "SubmitData.ProcHandReason": children[0].VALUE
              });
            } else if (type === 'SolveWay') {
              this.setData({
                SolveWayList: children,
                // "SubmitData.SOLVEWAY": children[0].VALUE
              });
            }
          }
        }
      });
    },
    GetComplainCount(){
      http.GetComplainCount({ ConsNo: this.data.orderinfo.ConsNo }).then(res => {
        if(res.code === 200){
          this.setData({
            "SubmitData.COMPLAINCOUNT": res.data ? res.data.ComplainCount : null
          });
        }
      })
    },
    ProcHandReasonRadioChange(e) {
      this.setData({
        "SubmitData.ProcHandReason": e.detail.value
      });
    },
    OtherReasonChange: function (e) {
      this.setData({
        "SubmitData.OTHERREASON": e.detail.value
      });
    },
    SolveWayRadioChange(e) {
      this.setData({
        "SubmitData.SOLVEWAY": e.detail.value
      });
    },
    SolveRemarkChange: function (e) {
      this.setData({
        "SubmitData.SOLVEREMARK": e.detail.value
      });
    },
    NormalFlagRadioChange(e) {
      this.setData({
        "SubmitData.NormalFlag": e.detail.value
      });
    },
    PetitionFlagRadioChange(e) {
      this.setData({
        "SubmitData.PetitionFlag": e.detail.value
      });
    },
    setDefaultValue() {
      this.setData({
        "SubmitData.SOLVEWAY": this.data.orderinfo.SolveWay,
        "SubmitData.SOLVEREMARK": this.data.orderinfo.SolveRemark,
        "SubmitData.ProcHandReason": this.data.orderinfo.ProcHandReason,
        "SubmitData.OTHERREASON": this.data.orderinfo.OtherReason,
        "SubmitData.NormalFlag": this.data.orderinfo.NormalFlag == null ? '0' : this.data.orderinfo.NormalFlag,
        "SubmitData.PetitionFlag": this.data.orderinfo.PetitionFlag == null ? '0' : this.data.orderinfo.PetitionFlag
      });
      const WorkOrderTempInfo = this.data.orderinfo.WorkOrderTempInfo;
      if (WorkOrderTempInfo) {
        this.setData({
          "SubmitData.BeginTime": WorkOrderTempInfo.BeginTime,
          "SubmitData.EndTime": WorkOrderTempInfo.EndTime,
          "SubmitData.HeatSide1Temp": WorkOrderTempInfo.HeatSide1Temp,
          "SubmitData.HeatSide1BackTemp": WorkOrderTempInfo.HeatSide1BackTemp,
          "SubmitData.HeatSide2Temp": WorkOrderTempInfo.HeatSide2Temp,
          "SubmitData.HeatSide2BackTemp": WorkOrderTempInfo.HeatSide2BackTemp,
          "SubmitData.OuterTemp": WorkOrderTempInfo.OuterTemp,
          "SubmitData.DeviceTemp": WorkOrderTempInfo.DeviceTemp,
          "SubmitData.LivingRoomTemp": WorkOrderTempInfo.LivingRoomTemp,
          "SubmitData.BedroomTemp": WorkOrderTempInfo.BedroomTemp,
          "SubmitData.SupplyTemp": WorkOrderTempInfo.SupplyTemp,
          "SubmitData.ReturnTemp": WorkOrderTempInfo.ReturnTemp,
          showUserSign: WorkOrderTempInfo.UserSign ? true : false,
          "SubmitData.ACCUMBACKFEEDAYS": WorkOrderTempInfo.AccumBackFeeDays,
          "SubmitData.COMPLAINCOUNT": WorkOrderTempInfo.ComplainCount,
        });
      }
      if (this.data.orderinfo.WeatherInfo) {
        this.setData({
          "SubmitData.OuterTemp": this.data.orderinfo.WeatherInfo.Temperature
        });
      }
    },
    /*********************日期选择************* */
    changeBeginTime: function (e) {
      this.setData({
        "SubmitData.BeginTime": e.detail.currentDateTimeStr
      });
    },
    changeEndTime: function (e) {
      this.setData({
        "SubmitData.EndTime": e.detail.currentDateTimeStr
      });
    },
    /*********************日期选择************* */
    /*********************测温************* */
    tempChange: function (e) {
      const type = parseInt(e.currentTarget.dataset.type);
      let val = e.detail.value
      val = val.replace(/[^\d.-]/g, ""); //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      if (type === 1) {
        this.setData({
          "SubmitData.OuterTemp": val
        });
      } else if (type === 2) {
        this.setData({
          "SubmitData.DeviceTemp": val
        });
      } else if (type === 3) {
        this.setData({
          "SubmitData.LivingRoomTemp": val
        });
      } else if (type === 4) {
        this.setData({
          "SubmitData.BedroomTemp": val
        });
      } else if (type === 5) {
        this.setData({
          "SubmitData.SupplyTemp": val
        });
      } else if (type === 6) {
        this.setData({
          "SubmitData.ReturnTemp": val
        });
      } else if (type === 7) {
        this.setData({
          "SubmitData.ACCUMBACKFEEDAYS": val
        });
      } else if (type === 8) {
        this.setData({
          "SubmitData.HeatSide1Temp": val
        });
      } else if (type === 9) {
        this.setData({
          "SubmitData.HeatSide1BackTemp": val
        });
      } else if (type === 10) {
        this.setData({
          "SubmitData.HeatSide2Temp": val
        });
      } else if (type === 11) {
        this.setData({
          "SubmitData.HeatSide2BackTemp": val
        });
      }
      console.log(this.data.SubmitData);
    },
    /*********************测温************* */
    /*********************电子签名************* */
    //画布初始化执行
    startCanvas() {
      var that = this;
      wx.getSystemInfo({
        success: function (res) {
          canvasw = res.windowWidth;
          canvash = res.windowHeight;
          // that.setData({
          //   canvasw: canvasw,
          //   canvash: canvash
          // });
        }
      });
      this.initCanvas();
      this.cleardraw();
    },
    //初始化函数
    initCanvas() {
      context = wx.createCanvasContext('canvas', this);
      context.beginPath()
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.setLineWidth(4);
      context.setLineCap('round');
      context.setLineJoin('round');
    },
    canvasStart(event) {
      isButtonDown = true;
      arrz.push(0);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    },
    canvasMove(event) {
      if (isButtonDown) {
        arrz.push(1);
        arrx.push(event.changedTouches[0].x);
        arry.push(event.changedTouches[0].y);
      }
      for (var i = 0; i < arrx.length; i++) {
        if (arrz[i] == 0) {
          context.moveTo(arrx[i], arry[i])
        } else {
          context.lineTo(arrx[i], arry[i])
        }
      }
      context.clearRect(0, 0, canvasw, canvash);
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.setLineWidth(3);
      context.setLineCap('round');
      context.setLineJoin('round');
      context.stroke();
      context.draw(false);
    },
    canvasEnd(event) {
      isButtonDown = false;
    },
    //清除画布
    cleardraw() {
      arrx = [];
      arry = [];
      arrz = [];
      context.clearRect(0, 0, canvasw, canvash);
      if (this.data.sysType === 'iOS') {
        context.fillStyle = 'rgba(255, 255, 255, 1)';
        context.setStrokeStyle('#444');
      } else {
        context.fillStyle = 'rgba(0, 0, 0, 1)';
        context.setStrokeStyle('#aaa');
      }
      context.draw(true);
      this.setData({
        showUserSign: false
      });
    },
    uploadImg() {
      if (arrx.length === 0) {
        wx.showToast({
          title: '请先签名！',
          icon: 'error',
          duration: 2000
        })
        return
      }
      var that = this
      wx.showLoading({
        mask: true,
        title: '签名上传中...'
      });
      //生成图片
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'canvas',
          //设置输出图片的宽高
          fileType: 'jpg',
          quality: 1,
          success: function (res) {
            // canvas图片地址 res.tempFilePath
            let imgBase64 = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
            that.setData({
              signUrl: res.tempFilePath,
              signBase64: imgBase64
            })
            that.uploadSignImg(res.tempFilePath)
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
              showCancel: false
            });
          },
          complete: function () {

          }
        }, that)
      }, 3000)
    },
    uploadSignImg(path) {
      const token = wx.getStorageSync(config.storageKey.token)
      const xtoken = wx.getStorageSync(config.storageKey.xtoken)
      wx.uploadFile({
        url: config.baseUrl + '/api/Upload/Upload',
        method: "POST",
        header: {
          'Authorization': 'Bearer ' + token,
          'X-Authorization': 'Bearer ' + xtoken
        },
        filePath: path,
        name: 'file',
        success: (resf) => {
          if (resf.statusCode === 200) {
            // const resData = JSON.parse(resf.data).data;
            const resData = JSON.parse(resf.data);
            if(resData.code === 200){
              this.setData({
                signSurl: resData.data[0]
              })
              wx.showToast({
                title: '上传签名成功！',
                icon: "none",
                duration: 2000
              })
            }else{
              wx.showToast({
                title: '上传签名失败！',
                icon: "none",
                duration: 2000
              });
            }
          } else {
            wx.showToast({
              title: '上传签名失败！',
              icon: "none",
              duration: 2000
            });
          }
        }
      })
    },
    /*********************电子签名************* */
    getSubmitData(isCheck = true) {
      if(isCheck){
        if (this.data.SubmitData.SOLVEWAY == null || this.data.SubmitData.SOLVEWAY == '') {
          wx.showToast({
            title: '解决措施不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else{
          if(this.data.SubmitData.SOLVEWAY === '099'){
            if(this.data.SubmitData.SOLVEREMARK == null || this.data.SubmitData.SOLVEREMARK == ''){
              wx.showToast({
                title: '其他措施文字说明不能为空！',
                icon: 'none',
                duration: 2000
              });
              return null;
            }
          }
        }
        if (this.data.SubmitData.ProcHandReason == null || this.data.SubmitData.ProcHandReason == '') {
          wx.showToast({
            title: '不热原因不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else{
          if(this.data.SubmitData.ProcHandReason === '099'){
            if(this.data.SubmitData.OTHERREASON == null || this.data.SubmitData.OTHERREASON == ''){
              wx.showToast({
                title: '其他原因文字说明不能为空！',
                icon: 'none',
                duration: 2000
              });
              return null;
            }
          }
        }
      }
      const submitData = {
        ProcHandReason: this.data.SubmitData.ProcHandReason,
        OTHERREASON: this.data.SubmitData.OTHERREASON,
        SOLVEWAY: this.data.SubmitData.SOLVEWAY,
        SOLVEREMARK: this.data.SubmitData.SOLVEREMARK,
        NormalFlag: this.data.SubmitData.NormalFlag ? parseInt(this.data.SubmitData.NormalFlag) : null,
        PetitionFlag: this.data.SubmitData.PetitionFlag ? parseInt(this.data.SubmitData.PetitionFlag) : null,
      }
      if (isCheck) {
        if (this.data.SubmitData.HeatSide1Temp == null || this.data.SubmitData.HeatSide1Temp === '') {
          wx.showToast({
            title: '换热器一次侧供温不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.HeatSide1Temp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.HeatSide1Temp))){
          wx.showToast({
            title: '换热器一次侧供温格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.HeatSide1BackTemp == null || this.data.SubmitData.HeatSide1BackTemp === '') {
          wx.showToast({
            title: '换热器一次侧回温不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.HeatSide1BackTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.HeatSide1BackTemp))){
          wx.showToast({
            title: '换热器一次侧回温格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.HeatSide2Temp == null || this.data.SubmitData.HeatSide2Temp === '') {
          wx.showToast({
            title: '换热器二次侧供温不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.HeatSide12emp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.HeatSide2Temp))){
          wx.showToast({
            title: '换热器二次侧供温格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.HeatSide2BackTemp == null || this.data.SubmitData.HeatSide2BackTemp === '') {
          wx.showToast({
            title: '换热器二次侧回温不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.HeatSide2BackTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.HeatSide2BackTemp))){
          wx.showToast({
            title: '换热器二次侧回温格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.OuterTemp == null || this.data.SubmitData.OuterTemp === '') {
          wx.showToast({
            title: '室外温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.OuterTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.OuterTemp))){
          wx.showToast({
            title: '室外温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.DeviceTemp == null || this.data.SubmitData.DeviceTemp === '') {
          wx.showToast({
            title: '散热器温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.DeviceTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.DeviceTemp))){
          wx.showToast({
            title: '散热器温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.LivingRoomTemp == null || this.data.SubmitData.LivingRoomTemp === '') {
          wx.showToast({
            title: '客厅温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.LivingRoomTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.LivingRoomTemp))){
          wx.showToast({
            title: '客厅温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.BedroomTemp == null || this.data.SubmitData.BedroomTemp === '') {
          wx.showToast({
            title: '卧室温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.BedroomTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.BedroomTemp))){
          wx.showToast({
            title: '卧室温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.SupplyTemp == null || this.data.SubmitData.SupplyTemp === '') {
          wx.showToast({
            title: '供水立杠温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.SupplyTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.SupplyTemp))){
          wx.showToast({
            title: '供水立杠温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
        if (this.data.SubmitData.ReturnTemp == null || this.data.SubmitData.ReturnTemp === '') {
          wx.showToast({
            title: '回水立杠温度不能为空！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }else if((this.data.SubmitData.ReturnTemp + '').slice(0, 1) === '.' || isNaN(parseFloat(this.data.SubmitData.ReturnTemp))){
          wx.showToast({
            title: '回水立杠温度格式不正确！',
            icon: 'none',
            duration: 2000
          });
          return null;
        }
      }
      submitData.WorkOrderTempInfo = {
        BeginTime: this.data.SubmitData.BeginTime,
        EndTime: this.data.SubmitData.EndTime,
        HeatSide1Temp: this.data.SubmitData.HeatSide1Temp ? parseFloat(this.data.SubmitData.HeatSide1Temp) : null,
        HeatSide1BackTemp: this.data.SubmitData.HeatSide1BackTemp ? parseFloat(this.data.SubmitData.HeatSide1BackTemp) : null,
        HeatSide2Temp: this.data.SubmitData.HeatSide2Temp ? parseFloat(this.data.SubmitData.HeatSide2Temp) : null,
        HeatSide2BackTemp: this.data.SubmitData.HeatSide2BackTemp ? parseFloat(this.data.SubmitData.HeatSide2BackTemp) : null,
        OuterTemp: this.data.SubmitData.OuterTemp ? parseFloat(this.data.SubmitData.OuterTemp) : null,
        DeviceTemp: this.data.SubmitData.DeviceTemp ? parseFloat(this.data.SubmitData.DeviceTemp) : null,
        LivingRoomTemp: this.data.SubmitData.LivingRoomTemp ? parseFloat(this.data.SubmitData.LivingRoomTemp) : null,
        BedroomTemp: this.data.SubmitData.BedroomTemp ? parseFloat(this.data.SubmitData.BedroomTemp) : null,
        SupplyTemp: this.data.SubmitData.SupplyTemp ? parseFloat(this.data.SubmitData.SupplyTemp) : null,
        ReturnTemp: this.data.SubmitData.ReturnTemp ? parseFloat(this.data.SubmitData.ReturnTemp) : null,
        ACCUMBACKFEEDAYS: this.data.SubmitData.ACCUMBACKFEEDAYS,
        COMPLAINCOUNT: this.data.SubmitData.COMPLAINCOUNT,
      }
      if (isCheck) {
        if (this.data.orderinfo.WorkOrderTempInfo && this.data.orderinfo.WorkOrderTempInfo.UserSign) {
          // 已经签过，可以重新签名，也可以不签名
          if (this.data.signSurl !== "") {
            submitData.WorkOrderTempInfo.UserSign = {
              FileName: 'sign',
              FilePath: this.data.signSurl,
              Size: 200
            }
          }
        } else {
          if (this.data.signSurl === "") {
            wx.showToast({
              title: '请上传客户签字！',
              icon: 'none',
              duration: 2000
            });
            return null;
          }
          submitData.WorkOrderTempInfo.UserSign = {
            FileName: 'sign',
            FilePath: this.data.signSurl,
            Size: 200
          }
        }
      } else {
        submitData.WorkOrderTempInfo.UserSign = {
          FileName: 'sign',
          FilePath: this.data.signSurl,
          Size: 200
        }
      }
      return submitData;
    },
  }
})